import Vue from 'vue'

import Cookies from 'js-cookie'

import 'normalize.css/normalize.css' // a modern alternative to CSS resets

import Element from 'element-ui'
import './assets/styles/element-variables.scss'

import '@/assets/styles/index.scss' // global css
import '@/assets/styles/rds.scss' // rds css
import App from './App'
import store from './store'
import router from './router'
import permission from './directive/permission'

import './assets/icons' // icon
import './permission' // permission control
import { getDicts } from '@/api/system/dict/data'
import { getConfigKey } from '@/api/system/config'
import {
  parseTime,
  resetForm,
  addDateRange,
  selectDictLabel,
  download,
  handleTree,
  dataFormat
} from '@/utils/rds'
import Pagination from '@/components/Pagination'
import 'viewerjs/dist/viewer.css'
import VueViewer from 'v-viewer'
Vue.use(VueViewer)
import './dialogdrag'
import './preventReClick'
import './scrollbar'
import settings from './settings'
// 全局方法挂载
Vue.prototype.getDicts = getDicts
Vue.prototype.getConfigKey = getConfigKey
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.addDateRange = addDateRange
Vue.prototype.selectDictLabel = selectDictLabel
Vue.prototype.download = download
Vue.prototype.handleTree = handleTree
Vue.prototype.tempDicts = JSON.parse(sessionStorage.getItem('tempDicts')) || {}
Vue.prototype.$globalSearch = {}
Vue.prototype.settings = settings
//字典翻译
/**
 * @param {String} key 转换键值
 * @param {String/Number} val 属性值
 * @returns {String}
 */
Vue.prototype.dataFormat = dataFormat
// 更新临时字典
/**
 * @param {Array} data 待更新列表
 */
;(Vue.prototype.updateTempDicts = function(data) {
  data.forEach((item, index) => {
    if (this.tempDicts[item.prop] == undefined) {
      this.getDicts(item.prop).then(response => {
        if (response.data.length > 0) {
          this.tempDicts[item.prop] = response.data
        } else this.tempDicts[item.prop] = []
      })
    }
  })
  sessionStorage.setItem('tempDicts', JSON.stringify(this.tempDicts))
}),
  // 字符串表达式转换
  /**
   * @param {Object} obj 当前对象
   * @param {String} str 字符串表达式
   * @returns {Array}
   */
  (Vue.prototype.dynamicEval = function(obj, str) {
    let res = str
    if (JSON.stringify(obj) != '{}') {
      str.replace(
        /[\$]([a-zA-Z][a-zA-Z0-9\.]*)[\$]|\[img\]([a-zA-Z][a-zA-Z0-9\.]*)\[img\]|\[stateid\](.*)\[stateid\]/g,
        function(result, r1, r2, r3) {
          if (r1) {
            if (r1.indexOf('.') > -1) {
              let tempArr = r1.split('.')
              if (obj[tempArr[0]] != undefined) {
                res = res.replace(result, obj[tempArr[0]][tempArr[1]])
              } else {
                res = res.replace(result, 'false')
              }
            } else {
              if (obj[r1] != undefined) {
                res = res.replace(result, obj[r1])
              } else {
                res = res.replace(result, 'false')
              }
            }
          } else if (r2) res = res.replace(result, "'/static/image/" + r2 + "'")
          else if (r3) {
            res = res.replace(
              result,
              `'${dataFormat('stateid', obj.stateid)}'=='${r3}'`
            )
          }
          return res
        }
      )
    }
    return new Function('return ' + res)()
  }),
  // url地址转换
  /**
   * @param {Object} obj 转换对象
   * @param {String} url URL地址表达式
   * @returns {String}
   */
  (Vue.prototype.getUrl = function(url, obj = {}) {
    var res = url
    if (url.indexOf('{') != -1 || url.indexOf('[') != -1) {
      // 1  obj 不存在
      const projectid = this.$route.params.Id
      if (JSON.stringify(obj) == '{}') {
        url.replace(/[{]([a-zA-Z][a-zA-Z0-9\.]*)[}]/g, (result, r1) => {
          if (result.indexOf('.') > -1) {
            // console.log(this)
            let tempArr = r1.split('.')
            // console.log(tempArr)
            res = res.replace(result, this.selected[0][tempArr[1]])
          } else res = res.replace(result, projectid)
        })
      } else {
        //2 obj 存在
        if (!Array.isArray(obj)) {
          //2.1 obj 为对象
          url.replace(
            /[{]([a-zA-Z][a-zA-Z0-9]*)[}]|\[df\]([a-zA-Z][a-zA-Z0-9\.]*)\[df\]/g,
            function(result, r1, r2) {
              if (r1) {
                if (r1.indexOf('.') > -1) {
                  let tempArr = r1.split('.')
                  if (obj[tempArr[0]] != undefined)
                    res = res.replace(result, obj[tempArr[0]][tempArr[1]])
                } else {
                  if (obj[r1] != undefined) res = res.replace(result, obj[r1])
                }
              }
              if (r2) {
                if (r2.indexOf('.') > -1) {
                  let tempArr = r2.split('.')
                  let optionData = JSON.parse(
                    sessionStorage.getItem('optionsData')
                  )
                  let type
                  optionData[tempArr[0] + 'Options'].forEach((item, index) => {
                    if (item.id == obj.assignmentypeid) {
                      type = item
                      return
                    }
                  })
                  console.log(type)
                  res = res.replace(result, type[tempArr[1]])
                }
              }
            }
          )
        } else {
          //2.2 obj 为数组
          url.replace(/[{]([a-zA-Z][a-zA-Z0-9]*)[}]/g, function(result, r1) {
            var data = null
            if (r1.indexOf('.') > -1) {
              let tempArr = r1.split('.')
              // res = res.replace(result, obj[tempArr[0]][tempArr[1]])
              data = obj.map(item => item[tempArr[0]][tempArr[1]])
            } else {
              data = obj.map(item => item[r1])
            }
            res = res.replace(result, String(data))
          })
        }
      }
    }
    return res
  }),
  // 按钮条件判断
  (Vue.prototype.jugeCondition = function(condition, url = '', title = '') {
    let flag = true
    let route = '/pms'
    let info = '确定' + title
    switch (condition) {
      case 'unique': {
        if (this.ids.length != 1) {
          flag = false
          this.msgInfo('请选择一条数据')
        } else {
          info += ` "${this.selected[0].name ||
            this.selected[0].title ||
            this.selected[0].fileName ||
            this.selected[0].folderName ||
            this.selected[0].userName}"?`
          route += this.getUrl(url, this.selected[0])
        }
        break
      }
      case 'notnull': {
        if (this.ids.length == 0) {
          flag = false
          this.msgInfo('请选择数据')
        } else {
          info += ` "${this.selected[0].name ||
            this.selected[0].title ||
            this.selected[0].fileName ||
            this.selected[0].folderName ||
            this.selected[0].userName}"${this.ids.length > 1 ? '等' : ''}?`
          route += this.getUrl(url, this.selected)
        }
        break
      }
      case 'sameState': {
        if (!this.JugeSeletions().sameState) {
          flag = false
          this.msgInfo('请选择同一状态的数据')
        } else {
          info += ` "${this.selected[0].name ||
            this.selected[0].title ||
            this.selected[0].fileName ||
            this.selected[0].folderName ||
            this.selected[0].userName}"${this.ids.length > 1 ? '等' : ''}?`
          route += this.getUrl(url, this.selected)
        }
        break
      }
      case 'sameLevel': {
        if (!this.JugeSeletions().sameLevel) {
          flag = false
          this.msgInfo('请选择同一层级数据')
        } else {
          info += ` "${this.selected[0].name ||
            this.selected[0].title ||
            this.selected[0].fileName ||
            this.selected[0].folderName ||
            this.selected[0].userName}"${this.ids.length > 1 ? '等' : ''}?`
          route += this.getUrl(url, this.selected)
        }
        break
      }
      default: {
        route = '/pms' + this.getUrl(url)
        info += '?'
        break
      }
    }
    return { flag, route, info }
  }),
  // 判断所有者是否为当前用户
  (Vue.prototype.isMine = function(ownerid) {
    return ownerid == this.$store.state.user.userId
  })
// 选项判断
;(Vue.prototype.JugeSeletions = function() {
  let sameState
  let sameLevel
  this.selected.forEach((item, index) => {
    if (index == 0) {
      sameLevel = item.level
      sameState = item.stateid
    } else if (sameState || sameLevel) {
      if (sameLevel != item.level) sameLevel = false
      if (sameState != item.stateid) sameState = false
    } else return
  })
  return { sameState, sameLevel }
}),
  (Vue.prototype.msgSuccess = function(msg) {
    this.$message({ showClose: true, message: msg, type: 'success' })
  }),
  (Vue.prototype.msgError = function(msg) {
    this.$message({
      showClose: true,
      message: msg,
      type: 'error',
      duration: 2000
    })
  }),
  (Vue.prototype.msgInfo = function(msg) {
    this.$message.info(msg)
  }),
  // 刷新当前页
  (Vue.prototype.refreshCurrent = function() {
    this.$store.dispatch('tagsView/delCachedView', this.$route).then(() => {
      const { fullPath } = this.$route
      this.$nextTick(() => {
        this.$router.replace({
          path: '/redirect' + fullPath
        })
      })
    })
  }),
  // 全局组件挂载
  Vue.component('Pagination', Pagination)
Vue.use(permission)
/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online! ! !
 */

Vue.use(Element, {
  size: Cookies.get('size') || 'medium' // set element-ui default size
})

Vue.config.productionTip = false
// commonJuge('stateid',10000074)
var app = new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
router.afterEach((to, from) => {
  let params = to.query
  if (typeof params.pageParams == 'string') {
    params = JSON.parse(sessionStorage.getItem(to.path))
  }
  if (params && params.rowParams != {} && params.rowParams != undefined) {
    to.meta.pmatched = from.matched
  }
})
